<?php

namespace app\common\model\mycurrency;

use think\Exception;
use think\Model;
use traits\model\SoftDelete;


class OperateDistributionProfit extends Model
{

    //use SoftDelete;

    

    // 表名
    protected $name = 'mycurrency_operate_distribution_profit';

    // 追加属性
    protected $append = [
        'status_text',

    ];

    const STATUS_YIQUXIAO = -1;//分成状态 = 已取消
    const STATUS_WEIFENCHENG = 1;//分成状态 = 未分成
    const STATUS_FENCHENGZHONG = 2;//分成状态 = 分成中
    const STATUS_YIFENCHENG = 3;//分成状态 = 已分成

    /**
     * 处理分销逻辑
     * @param int $user_id 下单用户id
     * @param int $paid_dlready 分销基数
     * @param array $data 扩展数据
    */
    public static function divideInto($user_id,$paid_dlready,$data=[]){
        $residue = $paid_dlready;//剩余金额 = 分销基数 - 已分出金额 【拿着这个金额进行后面的代理商 门店分成】
        $distribution_user = OperateDistributionUser::where(['user_id' => $user_id,'deletetime' => null])->find();
        if ($distribution_user){
            if ($distribution_user['pid'] != 0 && $distribution_user['pid'] != null){
                $actual_income = self::establishProfit($distribution_user['pid'],$paid_dlready,1,$data);
                $residue -= $actual_income;
                if($distribution_user['ppid'] != 0 && $distribution_user['ppid'] != null){
                    $actual_income = self::establishProfit($distribution_user['ppid'],$paid_dlready,2,$data);
                    $residue -= $actual_income;
                }
            }
        }
        return $residue;
    }

    /**
     * 创建收益
     * @param int $p_distribution_user_id 分销员id
     * @param int $tra_amount 交易金额
     * @param int $level 层级
     * @param array $data 扩展数据
    */
    public static function establishProfit($p_distribution_user_id,$tra_amount,$level = 1,$data){
        $actual_income = 0;
        $config = OperateDistributionConfig::get(1);
        $p_distribution_user = OperateDistributionUser::get($p_distribution_user_id);
        if($p_distribution_user){
            $div_proportion = 0;
            if ($level == 1){
                $div_proportion = $config['noe_level_proportion'];
            }else if($level == 2){
                $div_proportion = $config['two_level_proportion'];
            }
            if ($div_proportion > 0){
                $actual_income = sprintf("%.2f",($tra_amount / 100) * $div_proportion) ;
                $increase = [
                    'distribution_user_id' => $p_distribution_user->id,
                    'tra_amount' => $tra_amount,
                    'div_proportion' => $div_proportion,
                    'actual_income' => $actual_income,
                    'memo' => '团队成员交易触发收益',
                    'status' => self::STATUS_WEIFENCHENG,
                    'addtotime' => time(),
                    'createtime' => time(),
                ];
                $increase = array_merge($increase,$data);
                $profit = self::create($increase);
                self::grantProfit($profit->id);
            }
        }
        return $actual_income;
    }

    /**
     * 发放收益
     * @param int $profit_id 收益记录id
    */
    public static function grantProfit($profit_id){
        $profit = self::where(['id' => $profit_id,'deletetime' => null])->lock(true)->find();
        if(!$profit){
            throw new Exception('收益记录不存在');
            return false;
        }
        if ($profit['status'] != self::STATUS_WEIFENCHENG){
            throw new Exception('收益记录非待分成状态');
            return false;
        }

        //修改分销记录状态
        $profit->status = self::STATUS_YIFENCHENG;
        $profit->divideintotime = time();
        $profit->save();

        //分销员余额处理
        OperateDistributionMoneylog::moneyChange($profit['distribution_user_id'],$profit['actual_income'],OperateDistributionMoneylog::TYPE_YONGHUXIAOFEI,[
            'memo' => $profit['memo'],
            'profit_id' => $profit->id,
        ]);
    }


    public function getAddtotimeAttr($value){
        return $value != null ? date('Y-m-d H:i:s', $value) : '';
    }

    public function getDivideintotimeAttr($value){
        return $value != null ? date('Y-m-d H:i:s', $value) : '';
    }


    public function getStatusList()
    {
        return ['-1' => __('已取消'),'1' => __('未分成'), '2' => __('分成中'), '3' => __('已分成')];
    }

    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }



}
